﻿using System.Linq;
using System.Web.Mvc;
using PagedList;
using ToyStore.Domain.Contracts.Tasks;
using ToyStore.Domain.Store;
using ToyStore.Infrastructure;
using ToyStore.Web.Mvc.Authentication;
using ToyStore.Web.Mvc.Controllers.ViewModels;
using MvcContrib;
using ToyStore.Tasks;
using System.Collections.Generic;

namespace ToyStore.Web.Mvc.Controllers
{
    public class ProductController : Controller
    {
        /// <summary>
        /// Dostep do bazy danych produktów
        /// </summary>
        private readonly IExRepository<Product> _productRepository;

    	private readonly IExRepository<OrderedProduct> _orderedProductsRepository; 

    	private readonly ICartTask _cartTask;


    	/// <summary>
    	/// Konstruktor.
    	/// </summary>
    	/// <param name="productRepository"> </param>
    	/// <param name="cartTask"> </param>
    	/// <param name="orderedProductsRepository"> </param>
    	public ProductController(IExRepository<Product> productRepository, ICartTask cartTask, IExRepository<OrderedProduct> orderedProductsRepository)
        {
        	_productRepository = productRepository;
        	_cartTask = cartTask;
        	_orderedProductsRepository = orderedProductsRepository;
        }

		/// <summary>
		/// Szczegóły.
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
        public ActionResult Details(int id)
        {
            var viewModel = _productRepository.Get(id);
            return View(viewModel);
        }
        
        /// <summary>
        /// Pobiera list produktów dla kategorii ze stronicowaniem
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="pageNumber"></param>
        /// <param name="itemsOnPage"></param>
        /// <returns></returns>
        public ActionResult GetProductsByCategory(int categoryId,int pageNumber = 1, int itemsOnPage = 6, EnumSortType sortType = EnumSortType.None)
        {
            ProductListViewModel viewModel = new ProductListViewModel();
            
            viewModel.CategoryId = categoryId;

            var list = _productRepository.GetQuery().Where(p => p.Categories.Where(c => c.Id == categoryId).Count() > 0);
            switch(sortType)
            {
                case EnumSortType.ByNameAsc:
                    list = list.OrderBy(p => p.Name);
                    break;
                case EnumSortType.ByNameDesc:
                    list = list.OrderByDescending(p => p.Name);
                    break;
                case EnumSortType.ByPriceAsc:
                    list = list.OrderBy(p => p.PriceNetto);
                    break;
                case EnumSortType.ByPriceDesc:
                    list = list.OrderByDescending(p => p.PriceNetto);
                    break;
                case EnumSortType.ByAddDateAsc:
                    list = list.OrderBy(p => p.CreationDate);
                    break;
                case EnumSortType.ByAddDateDesc:
                    list = list.OrderByDescending(p => p.CreationDate);
                    break;
            }

            viewModel.ProductsList = list.ToPagedList(pageNumber, itemsOnPage);

            if (HttpContext.Session[CartTask.CartSessionGuid] != null)
            {
               Cart cartFromSession = (Cart)HttpContext.Session[CartTask.CartSessionGuid];
               viewModel.ProductsInUserCard = _cartTask.GetProductsInUserCart(cartFromSession.CartGuid);
            }
            List<SelectListItem> sortTypes = new List<SelectListItem>();
            sortTypes.Add(new SelectListItem() { Text = "Po nazwie : od A", Value = EnumSortType.ByNameAsc.ToString() });
            sortTypes.Add(new SelectListItem() { Text = "Po nazwie : od Z", Value = EnumSortType.ByNameDesc.ToString() });
            sortTypes.Add(new SelectListItem() { Text = "Po cenie : rosnąco", Value = EnumSortType.ByPriceAsc.ToString() });
            sortTypes.Add(new SelectListItem() { Text = "Po cenie : malejąco", Value = EnumSortType.ByPriceDesc.ToString() });
            sortTypes.Add(new SelectListItem() { Text = "Po dacie dodania : rosnąco", Value = EnumSortType.ByAddDateAsc.ToString() });
            sortTypes.Add(new SelectListItem() { Text = "Po dacie dodania : malejąco", Value = EnumSortType.ByAddDateDesc.ToString() });
            viewModel.SortTypes = sortTypes;
            viewModel.SelectedSortType = sortType;

            List<SelectListItem> itemsOnPageList = new List<SelectListItem>();
            itemsOnPageList.Add(new SelectListItem() { Text = "6", Value = "6" });
            itemsOnPageList.Add(new SelectListItem() { Text = "10", Value = "10" });
            itemsOnPageList.Add(new SelectListItem() { Text = "20", Value = "20" });
            itemsOnPageList.Add(new SelectListItem() { Text = "50", Value = "50" });
            itemsOnPageList.Add(new SelectListItem() { Text = "100", Value = "100" });
            viewModel.ItemsOnPageList = itemsOnPageList;
            viewModel.ItemsOnPage = itemsOnPage;

            
            return View(viewModel);
        }
        /// <summary>
        /// Wyszukiwanie ajaxowe produktów
        /// </summary>
        /// <returns></returns>
        public ActionResult SearchProductsAjax(string term)
        {
            var products = (from p in _productRepository.GetQuery()
                           where p.Name.Contains(term)
                           select new { p.Id, p.Name, p.PriceNetto, Url = "http://www.audiobook.pl/photo/product_small/0/1/6/1_016f682762ad.jpg" }).Take(10);

            return Json(products, JsonRequestBehavior.AllowGet);
        }

		/// <summary>
		/// Wyświetlanie półki użytkownika.
		/// </summary>
		/// <returns></returns>
		[HttpGet]
		public ActionResult YourShelf(int pageNumber, int itemsOnPage)
		{
			if(RightPrincipal.CurrentUser == null)
			{
				this.RedirectToAction<HomeController>(c => c.Index());
			}

			ProductListViewModel viewModel = new ProductListViewModel();
			viewModel.ItemsOnPage = itemsOnPage;

			// Wyszukujemy po zamowieniach produktow danego uzytkownika i zwracamy produkty.
			viewModel.ProductsList = _orderedProductsRepository.GetQuery().Where(c => c.Order.User.Id == RightPrincipal.CurrentUser.Id)
				.Select(c => c.Product).ToPagedList(pageNumber, itemsOnPage);
			return View(viewModel);
		}
    }
}
